<?php

namespace App\Repositories;

use App\Enum\DriverEnum;
use App\Models\DriverOthers;
use App\Models\Drivers;
use App\Models\Orders;
use BobCoder\Construct\Foundation\Repository\Repository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use PhpParser\Node\Expr\Cast\Object_;

class DriverRepository extends Repository
{
    protected $model;

    public function __construct()
    {
        $this->model = new Drivers();
    }


    /**
     * 司机列表
     * @param int $companyId 公司ID
     * @param string $realName 真实姓名
     * @param string $phone 手机号
     * @param string $identity 身份证
     * @param string $status 状态
     * @param int $pageSize
     *
     * @param array $columns
     * @return mixed
     * @Author 姿势就是力量
     */
    public function getPageList(int $companyId, int $province, int $city, string $realName, string $phone, string $identity, string $status, string $number, string $date, int $pageSize, array $columns = ['*'])
    {
        $type = '1';
        $list = Drivers::query()
            ->company($companyId)
            ->select($columns)
            ->with(['company:id,name', 'car:id,number', 'city:id,merger_name', 'auditor:id,name'])
            ->when($phone, function ($query) use ($phone) {
                $query->where('phone', 'like', '%' . $phone . '%');
            })
            ->when($province, function ($query) use ($province) {
                $query->where('province', 'like', '%' . $province . '%');
            })
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', '%' . $city . '%');
            })
            ->when($realName, function ($query) use ($realName) {
                $query->where('real_name', 'like', '%' . $realName . '%');
            })
            ->when($type, function ($query) use ($type) {
                $query->where('type', 'like', '%' . $type . '%');
            })
            ->when($identity, function ($query) use ($identity) {
                $query->where('identity', 'like', '%' . $identity . '%');
            })
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->when($phone, function ($query) use ($phone) {
                $query->where('phone', 'like', '%' . $phone . '%');
            })
            ->when($date, function ($query) use ($date) {
                if ($date) {
                    $list = explode(',', $date);
                    $query->whereBetween('created_at', [$list[0], $list[1]]);  //时间选择
                }
            })
            ->when($number, function ($query) use ($number) {
                $query->whereHas('car', function ($query2) use ($number) {
                    $query2->where('number', 'like', '%' . $number . '%');            //车牌号
                });
            })
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate($pageSize)
            ->toArray();
        return $list;
    }

    /**
     * 代驾司机列表
     */
    public function driving_list(int $companyId, int $city, string $realName, string $phone, string $identity, string $status, string $date, int $pageSize, int $province)
    {
        $list = DriverOthers::query()
            ->company($companyId)
            ->select(['id', 'company_id', 'driver_id', 'status', 'created_at', 'city'])
            ->with(['driver:id,real_name,phone,identity,province', 'companys:id,name', 'citys:id,merger_name'])
            ->when($identity, function ($query) use ($identity) {
                return $query->whereHas('driver', function ($query) use ($identity) {
                    return $query->where('identity', 'like', '%' . $identity . '%');
                });
            })
            ->when($phone, function ($query) use ($phone) {
                return $query->whereHas('driver', function ($query) use ($phone) {
                    return $query->where('phone', 'like', '%' . $phone . '%');
                });
            })
            ->when($realName, function ($query) use ($realName) {
                return $query->whereHas('driver', function ($query) use ($realName) {
                    return $query->where('real_name', 'like', '%' . $realName . '%');
                });
            })
            ->when($date, function ($query) use ($date) {
                if ($date) {
                    $list = explode(',', $date);
                    $query->whereBetween('created_at', [$list[0], $list[1]]);  //时间选择
                }
            })
            ->when($province, function ($query) use ($province) {
                return $query->whereHas('driver', function ($query) use ($province) {
                    return $query->where('province', 'like', '%' . $province . '%');
                });
            })
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', '%' . $city . '%');            //市id
            })
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);                             //状态
            })
            ->orderByDesc('id')
            ->orderByDesc('created_at')
            ->paginate($pageSize);
        return $this->list_arr($list);
    }

    /**
     * @param object $list
     */
    private function list_arr(object $list)
    {
        foreach ($list as $key => $value) {
            $list[$key]['id'] = $value['driver_id'];
            $list[$key]['real_name'] = $value['driver'] ? $value['driver']['real_name'] : '';
            $list[$key]['phone'] = $value['driver'] ? $value['driver']['phone'] : '';
            $list[$key]['identity'] = $value['driver'] ? $value['driver']['identity'] : '';
            $list[$key]['status'] = DriverEnum::statusMessage($value['status']);
            $list[$key]['company_id'] = $value['company_id'];
            $list[$key]['city'] = $value['citys'] ? $value['citys']['merger_name'] : '';
            $list[$key]['created_at'] = $value['created_at'];
            $list[$key]['company'] = $value['companys'] ? $value['companys']['name'] : '';
            $list[$key]['order'] = Orders::query()->where(['type' => '1', 'driver_id' => $value['driver_id']])->whereIn('status', ['4', '5', '6'])->count();
            unset($list[$key]['driver'], $list[$key]['citys'], $list[$key]['companys']);
        }
        return $list;
    }

    //导出司机
    public function excelPageList(int $companyId, $companyIds, int $province, int $city, string $realName, string $phone, string $identity, string $status, string $number, string $date, array $columns = ['*'])
    {
        return $this->model->select($columns)
            ->with(['company:id,name', 'car:id,number,host', 'city:id,merger_name', 'auditor:id,name'])
            ->when($realName, function ($query) use ($realName) {
                $query->where('real_name', 'like', '%' . $realName . '%');   //司机姓名
            })->when($companyId, function ($query) use ($companyId) {
                $query->where('company_id', $companyId);         //公司
            })
            ->when($phone, function ($query) use ($phone) {
                $query->where('phone', 'like', '%' . $phone . '%');           //司机电话
            })->when($identity, function ($query) use ($identity) {
                $query->where('identity', 'like', '%' . $identity . '%');      //身份证
            })->when($status, function ($query) use ($status) {
                $query->where('status', $status);                             //状态
            })
            ->when($number, function ($query) use ($number) {
                $query->whereHas('car', function ($query2) use ($number) {
                    $query2->where('number', 'like', '%' . $number . '%');            //车牌号
                });
            })
            ->when($province, function ($query) use ($province) {
                $query->where('province', 'like', '%' . $province . '%');             //省id
            })
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', '%' . $city . '%');            //市id
            })
            ->when($date, function ($query) use ($date) {
                if ($date) {
                    $list = explode(',', $date);
                    $query->whereBetween('created_at', [$list[0], $list[1]]);  //时间选择
                }
            })
            ->whereIn('company_id', $companyIds)
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 代驾司机导出
     */
    public function carExcels(int $companyId, $companyIds, int $city, string $realName, string $phone, string $identity, string $status, string $date)
    {
        $list = DriverOthers::query()
            ->select(['id', 'company_id', 'driver_id', 'status', 'created_at', 'city', 'company_id'])
            ->with(['driver:id,real_name,phone,identity', 'companys:id,name', 'citys:id,merger_name'])
            ->when($companyId, function ($query) use ($companyId) {
                return $query->whereHas('companys', function ($query) use ($companyId) {
                    return $query->where('id', $companyId);
                });
            })
            ->when($realName, function ($query) use ($realName) {
                return $query->whereHas('driver', function ($query) use ($realName) {
                    return $query->where('real_name', 'like', '%' . $realName . '%');
                });
            })
            ->when($phone, function ($query) use ($phone) {
                return $query->whereHas('driver', function ($query) use ($phone) {
                    return $query->where('phone', 'like', '%' . $phone . '%');
                });
            })
            ->when($identity, function ($query) use ($identity) {
                return $query->whereHas('driver', function ($query) use ($identity) {
                    return $query->where('identity', 'like', '%' . $identity . '%');
                });
            })
            ->when($date, function ($query) use ($date) {
                if ($date) {
                    $list = explode(',', $date);
                    $query->whereBetween('created_at', [$list[0], $list[1]]);  //时间选择
                }
            })
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);                             //状态
            })
            ->when($city, function ($query) use ($city) {
                $query->where('city', 'like', '%' . $city . '%');            //市id
            })
            ->whereIn('company_id', $companyIds)
            ->orderBy('created_at', 'desc')
            ->get()->toArray();
        $arr = [];
        foreach ($list as $item => $value) {
            $arr[$item]['merger_name'] = $value['citys']['merger_name'] ? $value['citys']['merger_name'] : '';
            $arr[$item]['company_name'] = $value['companys']['name'] ? $value['companys']['name'] : '';
            $arr[$item]['driver_name'] = $value['driver']['real_name'] ? $value['driver']['real_name'] : '';
            $arr[$item]['driver_id'] = $value['driver']['id'] ? $value['driver']['id'] : '';
            $arr[$item]['phone'] = $value['driver']['phone'] ? $value['driver']['phone'] : '';
            $arr[$item]['identity'] = $value['driver']['identity'] ? $value['driver']['identity'] : '';
            $arr[$item]['status'] = DriverEnum::statusMessage($value['status']);
            $arr[$item]['created_at'] = $value['created_at'];
        }
        return $arr;
    }

    /**
     * 司机详情
     * @param int $driverId 司机ID
     * @return mixed
     * @Author 姿势就是力量
     */

    public function getFirst(int $driverId)
    {
        return $this->model
            ->with([
                'head:id,file_url,file_name',
                'car:id,number,ownership,company_id,colour,restriction,brand_id,people,type,host',
                'wallet:driver_id,type,account,account_name,bank_name,phone',
            ])->withCount('comment')
            ->find($driverId);
    }

    /**
     * 代驾司机详情
     */
    public function details(int $driver_id)
    {

        return DriverOthers::query()
            ->select(['id', 'company_id', 'driver_id', 'status', 'province', 'city', 'identity_photo', 'licence_photo', 'source'])
            ->where('driver_id', $driver_id)
            ->with([
                'driver:id,phone,real_name,sex,user_id,identity,referrer_id',
                'company:id,name,short_name',
                'city:id,pid,shortname,name,merger_name',
            ])->withCount('comment')
            ->first();
    }

    /**
     * 保存信息
     * @param $params
     * @return Drivers|Collection|Model
     * @Author 姿势就是力量
     */
    public function saveData($params)
    {
        if (!empty($params['id'])) {
            $model = $this->find($params['id']);
        } else {
            $model = $this->model;
        }

        foreach ($params as $key => $value) {
            $model->{$key} = $value;
        }
        $model->save();

        return $model;
    }


    /**
     * 司机列表
     * @param string $search 司机手机号、姓名
     * @param array $columns
     * @return mixed
     * @Author 姿势就是力量
     */
    public function getList(string $search, array $columns = ['*'])
    {
        return $this->model
            ->select($columns)
            ->company()
            ->when($search, function ($query) use ($search) {
                $query->where('phone', 'like', '%' . $search . '%')->orWhere('real_name', 'like', '%' . $search . '%');
            })->pagination()
            ->get();
    }
}
